package data;

import java.sql.PreparedStatement;
import java.sql.SQLException;

import android.app.Activity;

/**
 * This class adds an Account to the database
 * 
 * @author Pooja
 */
public class AddAccount extends DBBooleanTask<Account> {

	/** the account to be added to the database */
	private Account acct;

	/**
	 * Takes in an activity and and the account to add
	 * 
	 * @param activity
	 *            - the activity for the loading bar
	 * @param acc
	 *            - the account
	 * @throws DBInterfaceError
	 */
	public AddAccount(Activity activity, Account acc) throws DBInterfaceError {
		super(activity, acc);
		this.acct = acc;

		if (acct.getAccountName() == null || acct.getAccountName().equals("")) {
			throw new DBInterfaceError(
					DBInterfaceError.Error.ACCOUNT_CREATION_INVALID_NAME);
		}

		if (acct.getPassword() == null || acct.getPassword().equals("")) {
			throw new DBInterfaceError(
					DBInterfaceError.Error.ACCOUNT_CREATION_INVALID_PASSWORD);
		}

		if (new AccountExists(activity, acc).getResult()) {
			throw new DBInterfaceError(
					DBInterfaceError.Error.ACCOUNT_CREATION_ACCOUNT_ALREADY_EXISTS);
		}
	}

	/**
	 * This task is the code that actually adds the account.
	 * 
	 * @param acct
	 *            the account to be added to the database
	 * @returns true if sucessfully added, false otherwise
	 */
	@Override
	protected boolean task(Account acct) {

		boolean success = true;

		try {
			PreparedStatement addAccountQuery;
			addAccountQuery = conn
					.prepareStatement("INSERT INTO account VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
			addAccountQuery.setString(1, acct.getAccountName());
			addAccountQuery.setString(2, acct.getPassword());
			addAccountQuery.setString(3, acct.getRealName());
			addAccountQuery.setString(4, acct.getEmail());
			addAccountQuery.setString(5, acct.getPhoneNumber());
			addAccountQuery.setInt(6, 0);
			addAccountQuery.setBoolean(7, false);
			addAccountQuery.setBoolean(8, false);

			if (!addAccountQuery.execute()) {
				if (addAccountQuery.getUpdateCount() == 0) {
					success = false;
				}
			}
		} catch (SQLException e) {
			success = false;
			System.err.println(e);
		}

		return success;
	}

}